package ynu.edu.Filter;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import ynu.edu.Util.JWTUtil;

import java.io.IOException;
import java.util.ArrayList;

@Component
@RequiredArgsConstructor
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {

        // 获取请求路径
        String path = request.getRequestURI();

        // 如果是登录接口或静态资源，直接放行
        if (path.startsWith("/user/login") || path.startsWith("/images/")) {
            filterChain.doFilter(request, response);
            return;
        }

        // 获取请求头中的token
        String authHeader = request.getHeader("Authorization");

        // 如果请求头中没有Authorization信息则直接返回
        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            response.setContentType("application/json;charset=UTF-8");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("{\"message\":\"未携带token或token格式错误\"}");
            return;
        }

        // 获取token
        String token = authHeader.substring(7);

        // 验证token
        if (!JWTUtil.verify(token)) {
            response.setContentType("application/json;charset=UTF-8");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("{\"message\":\"token无效或已过期\"}");
            return;
        }
        String username = JWTUtil.getName(token); // 假设你的JWTUtil有这个方法
        UsernamePasswordAuthenticationToken authentication =
                new UsernamePasswordAuthenticationToken(username, null, new ArrayList<>());
        SecurityContextHolder.getContext().setAuthentication(authentication);
        // token验证通过，继续执行
        filterChain.doFilter(request, response);
    }
}
